package com.dimples.security.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dimples.common.constant.StrPool;
import com.dimples.security.entity.SecurityUserDetails;
import com.dimples.system.entity.SysUser;
import com.dimples.system.service.SysMenuService;
import com.dimples.system.service.SysUserService;

import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2021/6/25
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DimplesUserDetailServiceImpl implements UserDetailsService {

    private final SysUserService sysUserService;
    private final SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户是否存在
        SysUser sysUser = sysUserService.getOne(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUsername, username));
        if (ObjectUtil.isEmpty(sysUser)) {
            log.debug("Query returned no results for user '" + username + "'");
            throw new UsernameNotFoundException(StrUtil.format("Username {} not found", username));
        }

        // 查询用户权限
        List<String> premissions = sysMenuService.findUserPermissions(username);
        SecurityUserDetails securityUserDetails = new SecurityUserDetails(sysUser.getUsername(), sysUser.getPassword(), true, true, true, StrUtil.equals(sysUser.getStatus(), SysUser.STATUS_VALID),
                AuthorityUtils.commaSeparatedStringToAuthorityList(StrUtil.join(StrPool.COMMA, premissions)));
        BeanUtil.copyProperties(sysUser, securityUserDetails);
        securityUserDetails.setLoginTime(DateUtil.formatDateTime(sysUser.getLastLoginTime()));
        return securityUserDetails;
    }
}